<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue'
import { v4 as uuidv4 } from 'uuid'
import startApi from "@/api/start.ts";
import store from "@/store";
import { useRouter } from 'vue-router'

const router = useRouter()
const loginForm = ref({
  userName: '',
  password: '',
  verifyCode: '',
  clientId: ''
});
const state = reactive({
  params: {
    init: { clientId: uuidv4() }
  },
  image: ''
})
onMounted(() => {
  captchaLoadHandle();
})
// 验证码加载
const captchaLoadHandle = () => {
  startApi.getCaptcha(state.params.init.clientId).then((res: any) => {
    state.image = 'data:image/gif;base64,' + res.data.pic
  })
}
// 登录
const onSubmit = (values: any) => {
  // 用户登录
  store.userStore.login({
    username: values.userName,
    password: values.password,
    clientId: state.params.init.clientId,
    verifyCode: values.verifyCode
  }).then(() => {
    router.replace({name: "My"});
  })
}
const { image } = toRefs(state)
</script>

<template>
  <div class="login-page">
    <div class="login-content">
      <van-nav-bar >
        <template #title>
          <div class="title">
            登录
          </div>
        </template>
      </van-nav-bar>
      <van-form @submit="onSubmit">
        <van-field v-model="loginForm.userName" name="userName" label="用户名" placeholder="请输入用户名" autocomplete="off"
                   :rules="[{ required: true, message: '请输入用户名', trigger: 'onBlur' }]" />
        <van-field v-model="loginForm.password" type="password" name="password" label="密码" placeholder="请输入密码" autocomplete="off"
                   :rules="[{ required: true, message: '请输入密码', trigger: 'onBlur' }]" />
        <van-field v-model="loginForm.verifyCode" name="verifyCode" label="验证码" placeholder="请输入验证码" center autocomplete="off"
                   :rules="[{ required: true, message: '请输入验证码', trigger: 'onBlur' }]" >
          <template #button>
            <img v-lazy="image" src="" width="100px" height="35px" alt="验证码" @click="captchaLoadHandle" />
          </template>
        </van-field>
        <div style="margin: 16px">
          <van-button block type="primary" native-type="submit">登录</van-button>
        </div>
      </van-form>
      <router-link to="/register" class="link">还没有账号,去注册</router-link>
    </div>
  </div>
</template>

<style lang="less" scoped>
.login-page {
  width: 100%;
  height: 100%;
  display: flex;
  overflow: hidden;
  background-image: url("~@/assets/images/login.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  opacity: 0.9;
  .login-content {
    margin: auto 10px;
    padding: 10px 10px 20px 10px;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    opacity: 0.9;
    .title{
      font-size: 20px;
      font-weight: 600;
    }
}

  .link {
    font-size: 12px;
    color: #069;
    float: right;
    margin-right: 15px;
}
}
</style>
